package com.cainli.image.gif;

import java.io.FileNotFoundException;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Handler;

import com.cainli.image.gif.GifDecoder.GifFrame;

/**
 * 
 * @author cainli 2013-1-31 下午4:42:55
 * 
 */
public class SyncGifDrawable extends AnimationDrawable{
	private static final String TAG = SyncGifDrawable.class.getSimpleName();
	public static final int DENSITY_NONE = 0;
	public static final int ASYNC_DECODE = 0x01;
	public static final int SYNC_DECODE = 0x02;
	private GifDecoder decoder = new GifDecoder();
	private Context context;
	private boolean hadDecoder = false;
	private boolean hadStart = false;
	private Handler mHandler = new Handler();
	public SyncGifDrawable(Context context, String path) {
		super();
		if (context == null) {
			throw new IllegalArgumentException("context can't null");
		}
		this.context = context;
		setOneShot(false);
		try {
			decoder.setPath(path);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void draw(Canvas canvas) {
		super.draw(canvas);
		Paint p = new Paint();
		p.setColor(0xffff00ff);
		p.setTextSize(64);
		canvas.drawText(""+getNumberOfFrames(), 100, 100, p);
		if(!hadDecoder){
			executeDecod();
			hadDecoder = true;
		}
		
	}
	
	@Override
	public void start() {
		if(!hadStart){
			super.start();
			hadStart = true;
		}
	}

	private void executeDecod() {
		new AsyncTask<Void, GifFrame, List<GifFrame>>(){
			@Override
			protected List<GifFrame> doInBackground(Void... params) {
				GifFrame nextFrame;
				try {
					nextFrame = decoder.nextFrame();
					while(nextFrame!=null){
						publishProgress(nextFrame);
						Thread.currentThread().sleep(5000);
						nextFrame = decoder.nextFrame();
					}
					return decoder.getFrames();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
			
			protected  void onProgressUpdate(final GifFrame[] values) {
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						addFrame(new BitmapDrawable(context.getResources(), values[0].image.get()), values[0].delay);
						invalidateSelf();
						start();
					}
				});
			};
		}.execute();
	}
	
}
